/*
 @desc: 磁盘保存
 @date: 2021/12/28
 */

#import "DiskStorage.h"

NSString * const dir = @"Pix";

@implementation DiskStorage

- (instancetype)init {
    self = [super init];
    if (self != nil) {
        [self prepareDirectory];
    }
    return self;
}

-(void)save:(UIImage *)image {
    NSDate * now = [NSDate new];
    NSTimeInterval dis = [now timeIntervalSince1970];
    NSString * key = [NSString stringWithFormat:@"%f.png",dis];
    NSURL * dir = [self targetDir];
    NSURL * final = [dir URLByAppendingPathComponent:key isDirectory:false];
    NSData * data = UIImagePNGRepresentation(image);
    BOOL flag = [data writeToURL:final options:NSDataWritingAtomic error:nil];
    NSLog(@"文件是否写入正常%d",flag);
}

- (NSArray *)fetchData {
    NSFileManager * fm = [NSFileManager defaultManager];
    NSURL * dir = [self targetDir];//NSURLResourceKey
    NSDirectoryEnumerator * en = [fm enumeratorAtURL:dir includingPropertiesForKeys:@[] options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:nil];
    NSArray * urls = en.allObjects;
    return  urls;
}

/// 获取目标文件地址
-(NSURL *)targetDir {
    NSFileManager * fm = [NSFileManager defaultManager];
    NSURL * first = [[fm URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] firstObject];
    NSURL * final = [first URLByAppendingPathComponent:dir isDirectory:true];
    return  final;
}

/// 创建存放内容的文件夹
-(void)prepareDirectory {
    NSFileManager * fm = [NSFileManager defaultManager];
    NSURL * final = [self targetDir];
    BOOL isExist = [fm fileExistsAtPath:final.path];
    if (isExist) {
        return;
    }
    BOOL flag = [fm createDirectoryAtURL:final withIntermediateDirectories:true attributes:nil error:nil];
    NSLog(@"创建文件:%id)",flag);
}

@end
